/*
 * Copyright(c) 2024 长沙市希尚网络科技有限公司
 * 注意：本内容仅限于长沙市希尚网络科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */

package org.example.security.controller;

import cn.hutool.extra.tokenizer.TokenizerUtil;
import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.security.core.TokenPreFilter;
import org.example.security.core.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.encrypt.BytesEncryptor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * TODO
 *
 * @author liuy
 * @version 1.0 2024/11/14 0014
 */
@RestController
@Slf4j
public class AuthController {

    @Autowired(required = false)
    private AuthenticationManager authenticationManager;

    //自定义登录接口
    @PostMapping("/auth/login")
    public String login(@RequestBody UserDTO userDTO, HttpSession httpSession) {
        // 根据源码可以知道，使用的Authentication其实是UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDTO.getUsername(),
            userDTO.getPassword());
        // 根据源码可以知道只有认证通过才会返回Authentication，其他会抛出异常

        Authentication authenticate = null;
        try {
            authenticate = authenticationManager.authenticate(authentication);
        } catch (AuthenticationException e) {
            throw new RuntimeException(e);
        }
        String tokenBySHA256 = "88888888";

        // 登录成功后生成token
        log.info("登录成功，生成token：{} ", tokenBySHA256);
        TokenPreFilter.tokenMap.put(tokenBySHA256, authenticate);

        SecurityContextHolder.getContext().setAuthentication(authenticate);
        return tokenBySHA256;
    }
}
